import axios from 'axios';
import { get } from '@/utils/auth';
import { ADMIN_KEY } from '@/utils/keys';
import store from '@/store';
import { Notification, MessageBox, Message, Loading } from 'element-ui';
import { tansParams, blobValidate } from '@/utils/ruoyi';
import { saveAs } from 'file-saver';

let downloadLoadingInstance;
let baseURL = process.env.VUE_APP_BASE_API || '/prod-api';
const HTTP_METHOD_PUT = 'PUT'
const HTTP_METHOD_DELETE = 'DELETE'
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8';
const myAxios = axios.create({
  baseURL: baseURL,
  timeout: 5000,
});

myAxios.interceptors.request.use(config => {
  const isToken = (config.headers || {}).isToken === false
  const token = get(ADMIN_KEY)

  if (config.type === 'map') {
    config.baseURL = process.env.VUE_APP_MAP_API
  }
  if (token && !isToken) {
    config.headers['Authorization'] = token
  }
  // put delete 特定处理
  switch (config.method.toUpperCase()) {
    case HTTP_METHOD_PUT:
      config.method = 'POST'
      config.headers['X-Http-Method-Override'] = HTTP_METHOD_PUT
      break
    case HTTP_METHOD_DELETE:
      config.method = 'POST'
      config.headers['X-Http-Method-Override'] = HTTP_METHOD_DELETE
      break
  }
  // get请求映射params参数
  if (config.method === 'get' && config.params) {
    let url = config.url + '?' + tansParams(config.params)
    url = url.slice(0, -1)
    config.params = {}
    config.url = url
  }
  return config
},
  error => {
    // 请求发生错误做什么
    return Promise.reject(error)
  }
);

myAxios.interceptors.response.use(config => {
  // 对响应数据做点什么
  const code = config.data.code || 200
  if (code === 401) {
    MessageBox.confirm('登录状态已过期，请重新登录', '系统提示', { confirmButtonText: '重新登录', cancelButtonText: '取消', type: 'warning' }).then(() => {
      store.dispatch('user/logOut').then(() => {
        location.href = '/web'
      });
    });
  } else if (500 === code) {
    Message.error(config.data.msg)
  } else if (601 === code) {
    Message.error(config.data.msg)
  } else {
    return config.data;
  }
}, error => {
  let { message } = error;
  if (message == 'Network Error') {
    message = '后端接口连接异常';
  } else if (message.includes('timeout')) {
    message = '系统接口请求超时';
  } else if (message.includes('Request failed with status code')) {
    message = '系统接口' + message.substr(message.length - 3) + '异常'
  }
  Message({ message: message, type: 'error', duration: 5 * 1000 })
  return Promise.reject(error)
}
)

// 通用下载方法
export function download (url, params, filename, config) {
  downloadLoadingInstance = Loading.service({ text: '正在下载数据，请稍候', spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.7)' })
  return myAxios
    .post(url, params, {
      transformRequest: [
        params => {
          return tansParams(params);
        },
      ],
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      responseType: 'blob',
      ...config,
    })
    .then(async data => {
      const isBlob = blobValidate(data)
      if (isBlob) {
        const blob = new Blob([data])
        saveAs(blob, filename)
      } else {
        const resText = await data.text()
        const rspObj = JSON.parse(resText)
        const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
        Message.error(errMsg)
      }
      downloadLoadingInstance.close()
    })
    .catch(r => {
      console.error(r)
      Message.error('下载文件出现错误，请联系管理员！')
      downloadLoadingInstance.close()
    })
}

export default myAxios;
